package com.wechatapp.mengyao.poetry.core;

import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yanghuaxu
 * @date 2025/5/21 9:09
 */
public class CurrentContext {

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal();
    private static final int LOCAL_MAP_SIZE = 8;

    public CurrentContext() {
    }

    private static void verifyThreadLocalMap() {
        Map<String, Object> map = (Map) THREAD_LOCAL.get();
        if (ObjectUtils.isEmpty(map)) {
            initThreadLocalMap();
        }

    }

    private static void initThreadLocalMap() {
        THREAD_LOCAL.set(new HashMap(LOCAL_MAP_SIZE));
    }

    public static void set(String key, Object value) {
        verifyThreadLocalMap();
        ((Map) THREAD_LOCAL.get()).put(key, value);
    }

    public static Object get(String key) {
        verifyThreadLocalMap();
        Object value = ((Map) THREAD_LOCAL.get()).get(key);
        return ObjectUtils.isEmpty(value) ? null : value;
    }


    public static void setCurrentOperatingUser(OperatingUser operatingUser) {
        set("user", operatingUser);
    }

    public static final OperatingUser getCurrentOperatingUser() {
        return ObjectUtils.isEmpty(get("user")) ? null : (OperatingUser) get("user");
    }

    public static final String getJWTToken() {
        return (String) get("x-auth-token");
    }

    public static void setJWTToken(String jwtToken) {
        set("x-auth-token", jwtToken);
    }

    public static void destroy() {
        THREAD_LOCAL.remove();
    }
}
